using System.Collections;
using Framework;
using UnityEngine;

public class GameChangeWorld : FsmStateAction
{
    private GameContext _gameContext;
    private MapGrid _map;
    private ResResult _sceneToken;
    protected override void OnAwake()
    {
        base.OnAwake();
    }
    protected override void OnEnter()
    {
        base.OnEnter();

        _gameContext = GameEntry.Context;
        _map = _gameContext.World.MapGrid;
        _map.Clear();
        GameEntry.Entity.Clear();
        GameEntry.Coroutine.Start(load());
        GameEntry.GUI.Open(GameEntry.GUIPath.LoadingUI);
        //GameEntry.GUI.Open(GameEntry.GUIPath.FpsUI);
    }
    protected override void OnExit()
    {
        base.OnExit();
        // GameEntry.GUI.Close(GameEntry.GUIPath.LoadingUI);
    }

    IEnumerator load()
    {
        if (_sceneToken != null)
        {
            GameEntry.AssetsLoader.Unload(_sceneToken);
            GameEntry.AssetsLoader.Unload();
            _sceneToken = null;
        }
        while (SceneConfig.Instance != null)
        {
            yield return null;
        }
        yield return null;
        var scene = GameEntry.Table.Scene.Get(_gameContext.CurrentSceneId);
        var result = GameEntry.AssetsLoader.LoadAsset(scene.Path);
        yield return result;
        _sceneToken = result;
        // while (!result.Result.SceneAsset.isDone)
        // {
        //     yield return null;
        // }
        // yield return null;
        result.SetSceneActive();
        var config = SceneConfig.Instance;
        _map.Set(config.AreaMin.position, config.AreaMax.position, 5);

        var exitCount = config.ExitPoint.Count;
        exitCount = Mathf.Min(exitCount, scene.ExitPoint.Length);
        for (var i = 0; i < exitCount; i++)
        {
            var point = config.ExitPoint[i];
            var p = GameEntry.Entity.Add<Door>("Assets/Res/Prefabs/P2.prefab");
            p.Pos = point.position;
            p.Exit = scene.ExitPoint[i];
        }
        this.Finished = true;
        if (scene.Id == 1)
        {
            GameEntry.GUI.Open(GameEntry.GUIPath.MainUI);
        }
        else
        {
            GameEntry.GUI.Close(GameEntry.GUIPath.MainUI);
        }

    }
}